<template>
  <a-modal
    :destroy-on-close="true"
    :mask-closable="false"
    title="应用管理编辑"
    :open="visible"
    :onCancel="onCancel"
    :width="800"
  >
    <template #footer>
      <a-button key="back" @click="() => onCancel()">取消</a-button>
      <a-button
        key="submit"
        type="primary"
        :loading="onSubmitLoading"
        @click="onFinish"
        >提交</a-button
      >
    </template>
    <a-form layout="vertical">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="应用编码" v-bind="validateInfos.appCode">
            <a-input
              v-model:value="modelRef.appCode"
              placeholder="请输入编码"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="应用名称" v-bind="validateInfos.name">
            <a-input v-model:value="modelRef.name" placeholder="请输入名称" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="应用英文名称" v-bind="validateInfos.nameEn">
            <a-input v-model:value="modelRef.nameEn" placeholder="请输入名称" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="应用负责人"
            v-bind="validateInfos.appUserInfoList"
          >
            <SearchStaff v-model:appUserInfoList="modelRef.appUserInfoList" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="路由前缀" v-bind="validateInfos.baseRoute">
            <a-input
              v-model:value="modelRef.baseRoute"
              placeholder="请输入路由前缀"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="默认页面">
            <a-input
              v-model:value="modelRef.defaultPage"
              placeholder="请输入默认页面"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="外域名地址">
            <a-input v-model:value="modelRef.exUrl" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="子内网域名地址" v-bind="validateInfos.url">
            <a-input v-model:value="modelRef.url" placeholder="请输入" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="icon附件">
            <a-upload
              name="avatar"
              list-type="picture-card"
              class="avatar-uploader"
              action=""
              :show-upload-list="false"
              :before-upload="beforeUpload"
              :auto-upload="false"
            >
              <img
                v-if="imageUrl"
                :width="102"
                :height="102"
                :src="imageUrl"
                alt="avatar"
              />
              <div v-else>
                <plus-outlined></plus-outlined>
                <div class="ant-upload-text">Upload</div>
              </div>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="keepAlive">
            <a-switch
              v-model:checked="modelRef.keepAlive"
              checked-children="ON"
              un-checked-children="OFF"
            />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="启用状态">
            <a-switch
              v-model:checked="modelRef.enableStatus"
              checked-children="ON"
              un-checked-children="OFF"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="是否集成统一审批">
            <a-switch
              v-model:checked="modelRef.integrationApprovalStatus"
              checkedValue="1"
              unCheckedValue="0"
              checked-children="ON"
              un-checked-children="OFF"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="modelRef.integrationApprovalStatus === '1'">
          <a-form-item
            label="集成统一审批API"
            v-bind="validateInfos.integrationApprovalApi"
          >
            <a-input
              v-model:value="modelRef.integrationApprovalApi"
              placeholder="请输入"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="是否集成统一任务">
            <a-switch
              v-model:checked="modelRef.integrationTaskStatus"
              checkedValue="1"
              unCheckedValue="0"
              checked-children="ON"
              un-checked-children="OFF"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="modelRef.integrationTaskStatus === '1'">
          <a-form-item
            label="集成统一任务API"
            v-bind="validateInfos.integrationTaskApi"
          >
            <a-input
              v-model:value="modelRef.integrationTaskApi"
              placeholder="请输入"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item label="描述">
            <a-textarea
              placeholder="请输入描述内容..."
              v-model:value="modelRef.remark"
              :rows="4"
              show-count
              :maxlength="100"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>
<script lang="ts">
import { defineComponent, PropType, reactive, Ref, ref } from "vue";
import { useI18n } from "vue-i18n";
import { message, Form } from "ant-design-vue";
import { validateInfos } from "ant-design-vue/lib/form/useForm";
const useForm = Form.useForm;
import { TableListItem } from "../data.d";
import { PlusOutlined } from "@ant-design/icons-vue";
import { uploadFile } from "@/utils/FileUpload";
import { Rule } from "ant-design-vue/lib/form/interface";
import SearchStaff from "@/components/SearchStaff/index.vue";

interface UpdateFormSetupData {
  modelRef: Omit<TableListItem, "id">;
  validateInfos: validateInfos;
  onFinish: () => Promise<void>;
  beforeUpload: (file: any) => Promise<void>;
  imageUrl: Ref<string>;
}
export default defineComponent({
  name: "CreateForm",
  components: {
    PlusOutlined,
    SearchStaff,
  },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    values: {
      type: Object as PropType<Partial<TableListItem>>,
      required: true,
    },
    onCancel: {
      type: Function,
      required: true,
    },
    onSubmitLoading: {
      type: Boolean,
      required: true,
    },
    onSubmit: {
      type: Function as PropType<(values: TableListItem) => void>,
      required: true,
    },
  },
  setup(props): UpdateFormSetupData {
    const { t } = useI18n();
    // 表单值
    let modelRef = reactive<TableListItem>({
      id: props.values.id || 0,
      appCode: props.values.appCode || "",
      name: props.values.name || "",
      nameEn: props.values.nameEn || "",
      url: props.values.url || "",
      exUrl: props.values.exUrl || "",
      icon: props.values.icon || "",
      label: props.values.label || "",
      defaultPage: props.values.defaultPage || "",
      baseRoute: props.values.baseRoute || "",
      enableStatus: props.values.enableStatus === "1" ? true : false,
      keepAlive: props.values.keepAlive || false,
      remark: props.values.remark || "",
      integrationApprovalStatus: props.values.integrationApprovalStatus || "0",
      integrationTaskStatus: props.values.integrationTaskStatus || "0",
      integrationApprovalApi: props.values.integrationApprovalApi || "",
      integrationTaskApi: props.values.integrationTaskApi || "",
      appUserInfoList: props.values.appUserInfoList || [],
    });

    const checkIntegrationApprovalApi = async (_rule: Rule, value: string) => {
      if (modelRef.integrationApprovalStatus === "1" && !value) {
        return Promise.reject("集成统一审批API不能为空");
      }
      return Promise.resolve();
    };

    const checkIntegrationTaskApi = async (_rule: Rule, value: string) => {
      if (modelRef.integrationTaskStatus === "1" && !value) {
        return Promise.reject("集成统一任务API不能为空");
      }
      return Promise.resolve();
    };
    // 表单验证
    const rulesRef = reactive({
      appCode: [
        {
          required: true,
          message: "编码不能为空",
        },
      ],
      name: [
        {
          required: true,
          message: "名称不能为空",
        },
      ],
      url: [
        {
          required: true,
          message: "子内网域名地址不能为空",
        },
      ],
      nameEn: [
        {
          required: true,
          message: "英文名称不能为空",
        },
      ],
      baseRoute: [
        {
          required: true,
          message: "路由前缀不能为空",
        },
      ],
      integrationApprovalApi: [
        {
          required: true,
          validator: checkIntegrationApprovalApi,
          trigger: "change",
        },
      ],
      integrationTaskApi: [
        {
          required: true,
          validator: checkIntegrationTaskApi,
          trigger: "change",
        },
      ],
      appUserInfoList: [
        {
          required: true,
          type: "array",
          message: "应用负责人不能为空",
          trigger: "change",
        },
      ],
    });

    // 获取表单内容
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );
    // 提交
    const onFinish = async () => {
      try {
        const fieldsValue = await validate<Omit<TableListItem, "id">>();
        modelRef.enableStatus = modelRef.enableStatus ? "1" : "0";
        props.onSubmit(modelRef);
      } catch (error) {
        message.warning(t("app.global.form.validatefields.catch"));
      }
    };
    const beforeUpload = async (file: any) => {
      console.log();
      const formData = new FormData();
      formData.append("file", file);
      formData.append("appId", "admin-service");
      const res = await uploadFile(formData);
      if (res.data.success) {
        imageUrl.value = res.data.data.extUrl;
        modelRef.icon = res.data.data.data.url;
      }
      return Promise.reject();
    };
    const imageUrl = ref(props.values.icon ? props.values.icon : "");
    return {
      modelRef,
      validateInfos,
      onFinish,
      beforeUpload,
      imageUrl,
    };
  },
});
</script>
